package com.example.lcode.backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Question40 {

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        combinationSum2(candidates, target, 0, res, new ArrayList<Integer>(), 0);
        return res;
    }

    private void combinationSum2(int[] candidates, int target, int calc, List<List<Integer>> res, List<Integer> re, int startIndex) {
        if (calc >= target) {
            if (calc == target) {
                res.add(new ArrayList<>(re));
            }
            return;
        }
        for (int i = startIndex; i < candidates.length ; i++) {
            if (i != 0 && candidates[i] == candidates[i - 1] && i != startIndex) {
                continue;
            }
            re.add(candidates[i]);
            combinationSum2(candidates, target, calc + candidates[i], res, re, i + 1);
            re.remove(re.size() - 1);
        }
    }

    public static void main(String[] args) {
        Question40 question40 = new Question40();
        int []arr = {2,5,2,1,2};
        int target = 5;
        List<List<Integer>> lists = question40.combinationSum2(arr, target);
        System.out.println(lists);
    }

}
